﻿using MyHostSwtich.Datas.Models;

using System.Collections.Generic;
using System.IO;

namespace MyHostSwtich.Core
{
    public class CommonRange
    {
        public static CommonRange Instance { get; private set; } = new CommonRange();

        private CommonRange()
        {
            HostRootPath = Utils.Instance.GetHostPath();
            LoadConfigs();
        }

        private void LoadConfigs()
        {
            this.Configs.Clear();
            InitDefault();

            var path = Path.GetDirectoryName("./configs/");
            var files = Directory.GetFiles(path, "*.config", SearchOption.TopDirectoryOnly);
            foreach(var filepath in files)
            {
                var filename = Path.GetFileName(filepath);
                var content = File.ReadAllText(filepath);
                var config = new ConfigItem(filepath, content);

                this.Configs.Add(filename, config);
            }
        }

        private void InitDefault()
        {
            var src = Path.Combine(HostRootPath, "hosts");
            var target = Path.GetFullPath("./configs/default.config");

            if(!File.Exists(target)) File.Copy(src, target);
        }

        public string HostRootPath { get; private set; } = string.Empty;

        public Dictionary<string, ConfigItem> Configs { get; set; } = new Dictionary<string, ConfigItem>();

    }

}
